import {computed, designPage} from "@peryl/react-compose";
import {useTableOption} from "../../modules/plain-design/useTableOption";
import {$previewer, AutoTable, Plc, PlcDate, PlcInput, PlcTextarea} from "plain-design";
import {CmsComponentEditor, iCmsComponentJsonData} from "../components/CmsComponentEditor";
import {PlainCmsNamespace} from "@peryl/react-cms-editor";
import {doNothing} from "@peryl/utils/doNothing";

export default designPage(() => {

  const cmsUseConfig: PlainCmsNamespace.iUseConfig = { isRunning: false, enableParamVariablesForCmsEditor: true };

  const option = useTableOption({
    url: '/cms_components',
    fill: true,
    bodyRowHeight: 70,
  });

  const jsonListData = computed(() => {
    // console.log('calculate jsonListData');
    const ret: iCmsComponentJsonData[] = [];
    option.state.list.forEach(i => {
      try {
        const jsonData: iCmsComponentJsonData | null = !i.jsonData ? null : JSON.parse(i.jsonData);
        if (!!jsonData) {ret.push(jsonData);}
      } catch (e) {
        console.error(e);
      }
    });
    return ret;
  });

  return () => <>
    <AutoTable option={option}>
      {/*不知道为啥这里不把这个计算属性放render里边就不会重新计算的问题，估计是个什么bug，这里去掉会导致预览图片的时候得到的不是最新的值*/}
      {doNothing(jsonListData.value)}

      <Plc title="预览图" field="previewImage" addEditPadding v-slots={{
        normal: ({ row, node }) => <CmsComponentEditor v-model={row.jsonData} valueTypeString disabled useConfig={cmsUseConfig} previewOnClick={false} onClick={(e) => {
          $previewer.preview({ current: node.state.index, urls: jsonListData.value.map(i => i.image) }, e.currentTarget as any);
        }}/>,
        edit: ({ row }) => <CmsComponentEditor v-model={row.jsonData} valueTypeString useConfig={cmsUseConfig}/>,
      }}/>
      <PlcInput title="名称" field="name" required/>
      <PlcDate title="创建时间" field="createdAt" hideInForm width={180} editable={false} datetime/>
      <PlcTextarea title="说明" field="description"/>
    </AutoTable>
  </>;
});

/*export default designPage(() => {
  const state = reactive({
    jsonData: undefined as undefined | string
  });
  return () => (
    <PageCard>
      <PageCardContent>
        <CmsComponentEditor v-model={state.jsonData} valueTypeString/>
      </PageCardContent>
    </PageCard>
  );
});*/
